package com.house.generator;

import lombok.extern.slf4j.Slf4j;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Slf4j
public class ConnectionUtils {

	public static String url = "jdbc:mysql://rm-cn-9lb37ei3k001e37o.rwlb.cn-chengdu.rds.aliyuncs.com:3306/house_test?useUnicode=true&useSSL=false&characterEncoding=utf-8&serverTimezone=UTC%2B8&allowPublicKeyRetrieval=true";

	public static String userName = "mysqlroot";

	public static String password = "MySQLroot@";

	public static String driverClassName = "com.mysql.cj.jdbc.Driver";

	public static List<String> getTableListWithPrefix(String... tablePrefrex) {
		List<String> allTable = getAllTable();
		if(tablePrefrex == null || tablePrefrex.length == 0) {
			return allTable;
		}
		return allTable.stream().filter(new Predicate<String>() {
			@Override
			public boolean test(String table) {
				boolean matches = false;
				for (String prefix : tablePrefrex) {
					if(table.startsWith(prefix)) {
						matches = true;
						break;
					}
				}
				return matches;
			}
		}).collect(Collectors.toList());
	}

	private static Connection getConnection(String driver, String url, String userName, String passWord) {
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, userName, passWord);
		} catch (Exception e) {
			log.error("ConnectionUtils getConnection caught exception :" + e.getStackTrace());
		}
		return conn;
	}

	public static List<String> getAllTable() {
		List<String> tableList = new ArrayList<>();

		try(Connection con = getConnection(driverClassName, url, userName, password)) {
			DatabaseMetaData meta = con.getMetaData();
			ResultSet rs = meta.getTables(null, null, null,
					new String[] { "TABLE" });
			while (rs.next()) {
				tableList.add(rs.getString("TABLE_NAME"));
			}
		} catch (Exception e) {
			log.error("ConnectionUtils getAllTable caught exception :" + e.getStackTrace());
		}
		return tableList;
	}

}
